<template>
  <div class="tab" ref="tab">
    <div
      class="tab-item"
      v-for="tab in tabs"
      :key="tab.name"
      :class="{'is-active':activeTab===tab.name}"
      @click="clickTab(tab.name)"
    >
      <span>
        {{tab.title}}
        <span class="close" @click.prevent="removeTab(tab.name)">x</span>
      </span>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TabIndex',
  data () {
    return {
      tabs: [{ name: 'Index', title: '首页', path: '/index' }],
      activeTab: 'Index'
    }
  },
  methods: {
    clickTab (tabName) {
      const currentTab = this.tabs.find(item => item.name === tabName)
      this.$router.push(currentTab.path)
    },
    removeTab (tabName) {
      if (tabName === this.activeTab) {
        // 需要确定激活的tab
        this.tabs.forEach((el, index) => {
          if (el.name === tabName) {
            const nextTab = this.tabs[index + 1] || this.tabs[index - 1]
            if (nextTab) {
              this.activeTab = nextTab.name
              this.$router.push(nextTab.path)
            }
          }
        })
      }

      this.tabs = this.tabs.filter(item => item.name !== tabName)
    }
  },
  watch: {
    $route () {
      const route = this.$route
      const i = this.tabs.findIndex(item => item.path === route.path)
      if (i === -1) {
        this.tabs.push({
          name: route.name,
          title: route.meta.title,
          path: route.path
        })
      }
      this.activeTab = route.name
    }
  }
}
</script>

<style lang="scss">
.tab {
  height: 40px;
  display: flex;
  border-bottom: 1px solid #d7d8d9;
  &-item {
    position: relative;
    height: 30px;
    font-size: 14px;
    line-height: 30px;
    margin: 5px 2px 0px;
    padding: 0px 5px 0px 8px;
    border: 1px solid #d7d8d9;
    &:first-child {
      padding: 0px 10px;
      .close {
        display: none;
      }
    }
    &:hover {
      cursor: pointer;
      color: #409eff;
    }
  }

  .close {
    display: inline-block;
    width: 15px;
    height: 15px;
    font-size: 10px;
    text-align: center;
    line-height: 15px;
    vertical-align: 2px;
    &:hover {
      border-radius: 50%;
      background-color: #f2f2ed;
    }
  }

  .is-active {
    color: #409eff;
    background-color: #d2e3f3;
  }
}
</style>
